<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" size="small" :inline="true">
      <el-form-item label="电话号码" prop="phone">
        <el-input v-model="queryParams.phone" placeholder="请输入电话号码" />
      </el-form-item>

      <el-form-item>
        <el-button
          type="primary"
          icon="el-icon-search"
          size="mini"
          @click="searchAction"
          >搜索</el-button
        >
        <el-button icon="el-icon-refresh" size="mini" @click="resetAction"
          >重置</el-button
        >
      </el-form-item>
    </el-form>

    <el-table v-loading="loading" :data="userList">
      <el-table-column label="ID" prop="id" width="100" />

      <el-table-column
        label="昵称"
        prop="nickName"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column
        label="电话"
        prop="phone"
        :show-overflow-tooltip="true"
        width="150"
      />
      <el-table-column label="性别" prop="gender" :show-overflow-tooltip="true">
        <template slot-scope="scope">
          {{
            scope.row.gender === 0
              ? "未知"
              : scope.row.gender === 1
              ? "男"
              : "女"
          }}
        </template>
      </el-table-column>
      <el-table-column label="模型材质" prop="mesh">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.mesh"
            style="width: 100px; height: 100px"
            :src="`${rootPath}/${scope.row.mesh}`"
            fit="cover"
            class="align-items_center justify_center"
          >
            <div slot="error" >
              <i class="el-icon-picture-outline"></i>
            </div>
          </el-image>
        </template>
      </el-table-column>

      <el-table-column
        label="操作"
        align="center"
        class-name="small-padding fixed-width"
      >
        <template slot-scope="scope" v-if="scope.row.roleId !== 1">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            >设置模型</el-button
          >
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="pagination.total > 0"
      :total="pagination.total"
      :page.sync="pagination.page"
      :limit.sync="pagination.pageSize"
      @pagination="paginationAction"
    />

    <!-- 添加或修改模型配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="500px" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="100px">
        <el-form-item label="模型材质" prop="mesh">
          <el-input v-model="form.mesh" placeholder="请输入模型材质" readonly>
            <label slot="suffix">
              <el-upload
                action=""
                :http-request="(event) => uploadFile('mesh', event)"
                :show-file-list="false"
              >
                <el-button icon="el-icon-upload2"></el-button>
              </el-upload>
            </label>
          </el-input>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getUsers, getUser, updateUser } from "@/api/user";
import { uploadFile } from "@/api/file";

const defaultPagination = {
  pageSize: 5,
  page: 1,
};

const defaultQuery = {
  phone: "",
};
function filterEmpty(target) {
  const result = Object.fromEntries(
    Object.entries(target).filter(([key, value]) => value)
  );
  return result;
}

export default {
  name: "User",
  data() {
    return {
      rootPath: process.env.VUE_APP_ROOT_PATH,
      // 遮罩层
      loading: true,
      // 模型表格数据
      userList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,

      pagination: {
        ...defaultPagination,
      },
      // 表单参数
      form: {},

      queryParams: {
        ...defaultQuery,
      },
      // 表单校验
      rules: {
        mesh: [{ required: true, message: "请上传模型材质", trigger: "blur" }],
      },
    };
  },
  created() {
    this.getUsers();
  },
  methods: {
    async uploadFile(target, event) {
      const formData = new FormData();
      formData.append("file", event.file);
      const { result } = await uploadFile(formData);
      this.form = {
        ...this.form,
        [target]: result,
      };
    },

    /** 查询模型列表 */
    getUsers(params = defaultPagination) {
      this.loading = true;

      getUsers({
        ...params,
        ...filterEmpty(this.queryParams),
      }).then(({ result, pagination }) => {
        this.userList = result;
        this.pagination = pagination;
        this.loading = false;
      });
    },
    paginationAction({ page, limit }) {
      this.getUsers({
        page,
        pageSize: limit,
      });
      console.log("event");
    },

    searchAction() {
      this.getUsers();
    },

    resetAction() {
      this.queryParams = {
        ...defaultQuery,
      };
      this.getUsers();
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },

    // 表单重置
    reset() {
      this.form = {};
      this.resetForm("form");
    },

    /** 修改按钮操作 */
    handleUpdate({ id }) {
      getUser(id).then(({ result }) => {
        this.form = result;
        console.log("this.form", this.form, result);
        this.open = true;
        this.title = "修改模型";
      });
    },

    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate((valid) => {
        if (valid) {
          if (this.form.id != undefined) {
            const { id, mesh } = this.form;
            updateUser(id, {
              mesh,
            }).then(() => {
              this.getUsers();
              this.open = false;
              this.$modal.msgSuccess("修改成功");
            });
          }
        }
      });
    },
  },
};
</script>
